package com.longkier.gx_library_springboot.Service;

import com.longkier.gx_library_springboot.entity.LibraryArea;
import com.longkier.gx_library_springboot.exception.CustomException;
import com.longkier.gx_library_springboot.repository.AreaRepository;
import com.longkier.gx_library_springboot.repository.BookRepository;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AreaService {

    private final AreaRepository areaRepository;
    private final BookRepository bookRepository;

    // 获取所有图书馆区域
    public List<LibraryArea> getAllLibraryAreas() {
        return areaRepository.findAll();
    }

    // 根据ID获取图书馆区域
    public Optional<LibraryArea> getLibraryAreaById(Long id) {
        return areaRepository.findById(id);
    }

    // 保存或更新图书馆区域
    public LibraryArea saveOrUpdateLibraryArea(@NotNull LibraryArea libraryArea) {
        if (libraryArea.getAreaCodeId() == null) {
            libraryArea.setCreateTime(LocalDateTime.now());
        }
        libraryArea.setUpdateTime(LocalDateTime.now());
        return areaRepository.save(libraryArea);
    }

    // 删除图书馆区域
    public void deleteLibraryArea(Long id) {
        @NotNull Optional<LibraryArea> libraryAreaOptional = areaRepository.findById(id);
        if (libraryAreaOptional.isPresent()) {
            LibraryArea libraryArea = libraryAreaOptional.get();
            String areaName = libraryArea.getAreaName();
            if (!bookRepository.existsByBookArea(areaName)) {
                areaRepository.deleteById(id);
            } else {
                throw new CustomException(500, "该图书馆区域下有图书，无法删除");
            }
        } else {
            throw new CustomException(500, "未找到该图书馆区域");
        }
    }
}
